﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wallpaper.Data.Context;
using Wallpaper.Data.Dal;
using Wallpaper.Data.IDal;
using Wallpaper.Models.DTOs.Responses;
using Wallpaper.Models.Entities;
using Wallpaper.Services.IService;

namespace Wallpaper.Services.Service
{
    public class PermissionService : IPermissionService
    {
        private readonly IPermissionDal _permissionDal;
        private readonly IMenuDal _menuDal;
        private readonly WallpaperDbContext _dbContext;

        public PermissionService(IPermissionDal permissionDal, WallpaperDbContext dbContext, IMenuDal menuDal)
        {
            _permissionDal = permissionDal;
            _dbContext = dbContext;
            _menuDal = menuDal;
        }


        /// <summary>
        /// 获取所有权限
        /// </summary>
        /// <returns></returns>
        public async Task<List<PermissionTreeResponse>> GetPermissionTreeAsync()
        {
            var menuList = await _menuDal.GetQueryable()
                .Where(m => !m.IsDeleted)
                .OrderBy(m => m.Sort)
                .ToListAsync();

            var permissionList = await _permissionDal.GetQueryable()
                .Where(p => !p.IsDeleted)
                .ToListAsync();

            return menuList
                .Select(menu => new PermissionTreeResponse
                {
                    Id = menu.Id,
                    Label = menu.Name,
                    Children = permissionList
                        .Where(p => p.MenuId == menu.Id)
                        .OrderBy(p => p.Sort)
                        .Select(p => new PermissionTreeResponse
                        {
                            Id = p.Id,
                            Label = p.Name
                        }).ToList()
                })
                .Where(m => m.Children.Any())
                .ToList();
        }






        /// <summary>
        /// 权限校验的核心。根据 JWT 传来的 roleCode 和方法所需的 requiredPermission，
        /// 连表查询 RolePermission，判断权限是否存在。
        /// </summary>
        /// <param name="roleCode"></param>
        /// <param name="requiredPermission"></param>
        /// <returns></returns>
        public async Task<bool> HasPermissionAsync(string roleCode, string requiredPermission)
        {
            // 连表查询：通过 RolePermission 中间表，同时检查 RoleCode 和 Permission Code
            var hasPermission = await _dbContext.RolePermissions
                // 连表到 Role 表，检查 RoleCode 是否匹配
                .Where(rp => rp.Role.RoleCode == roleCode)
                // 连表到 Permission 表，检查 Permission Code 是否匹配方法所需权限
                .Where(rp => rp.Permission.Code == requiredPermission)
                // 检查是否存在匹配的记录
                .AnyAsync();

            return hasPermission;
        }
    }
}
